package org.example.controller.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.URLEncodeUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.example.domain.Result;
import org.example.service.fileService.FileService;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;

/**
 * @description:
 * @Author: whopxx
 * @CreateTime: 2025-01-07
 */
@RestController
@RequestMapping("/document")
public class FileController {

    @Resource
    private FileService fileService;

    @GetMapping("/interface")
    public Result interfaceDocument(@RequestParam Integer pid) {
        String filename = fileService.generateInterfaceDocument(pid);
        // 等待两秒
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return Result.success(filename);
    }

    @GetMapping("/requirement")
    public Result requirementDocument(@RequestParam Integer pid) {
        String filename = fileService.generateRequirementDocument(pid);
        // 等待两秒
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return Result.success(filename);
    }

    @GetMapping("/download")
    public void download(@RequestParam String fileName, HttpServletResponse response) {
        try {
            File path = new File(ResourceUtils.getURL("classpath:static").getPath());
            if(!path.exists()) {
                path = new File("");
            }
            File file = new File(path.getAbsolutePath()+"/"+fileName);
            if(file.exists()){
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                String encodedFileName = URLEncodeUtil.encode(file.getName());
                response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
                try (
                        ServletOutputStream outputStream = response.getOutputStream();
                ) {
                    outputStream.write(FileUtil.readBytes(file));
                    outputStream.flush();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
